package com.eliota.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eliota.common.Constants;
import com.eliota.common.R;
import com.eliota.entity.Dict;
import com.eliota.entity.Menu;
import com.eliota.entity.Role;
import com.eliota.mapper.DictMapper;
import com.eliota.service.MenuService;
import com.eliota.service.RoleService;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author MG
 * @since 2023-03-28
 */
@RestController
@RequestMapping("/menu")
public class MenuController {


    @Resource
    private MenuService menuService;

    @Resource
    private DictMapper dictMapper;

    /**
     * 新增
     * @param menu
     * @return
     */
    @PostMapping("/save")
    public R save(@RequestBody Menu menu){
        menu.setStatue(1);
        return R.success(menuService.saveOrUpdate(menu));
    }

    @GetMapping("/list")
    public R findAll(){
        QueryWrapper<Menu> menuQueryWrapper = new QueryWrapper<>();
        menuQueryWrapper.eq("statue",1);
        return R.success(menuService.list(menuQueryWrapper));
    }

    @GetMapping
    public R findTree(@RequestParam String menuName){
        //menus和其childrenMenu
        List<Menu> menus = menuService.findMenus(menuName);
        return R.success(menus);
    }

    @DeleteMapping("/{id}")
    public R delete(@PathVariable Integer id){
        boolean isDel =  menuService.deleteById(id);
        if(isDel){
            System.out.println(isDel + ">>>>>>>>>>>>>.删除成功");
            return R.success();
        }else {
            System.out.println("》》》》》》》》》》》》删除失败");
            return R.error("删除失败");
        }
    }

    @PostMapping("/bath/del")
    public R deleteBath(@RequestBody List<Integer> ids){
        return R.success(menuService.deleteBathByIds(ids));
    }

    @GetMapping("/page")
    public R findPage(@RequestParam Integer pageNum,
                      @RequestParam Integer pageSize,
                      @RequestParam String menuName){
        Page<Menu> menuPage = new Page<>(pageNum, pageSize);
        QueryWrapper<Menu> menuQueryWrapper = new QueryWrapper<>();
        menuQueryWrapper.like("menu_name",menuName);
        menuQueryWrapper.eq("statue",1);

        return R.success(menuService.page(menuPage,menuQueryWrapper));
    }

    @GetMapping("/icons")
    public R getIcons(){
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("type", Constants.DICT_TYPE_ICON);
        return R.success(dictMapper.selectList(null));
    }

    @GetMapping("/ids")
    public R findAllIds(){
        System.out.println();
        return R.success(menuService.list().stream().map(Menu::getId));
    }
}
